//
//  MainViewController.m
//  SimpleTimeDemo
//
//  Created by lanou3g on 15/11/12.
//  Copyright © 2015年 王丽珍. All rights reserved.
//

#import "MainViewController.h"
#import "RESideMenu.h"
#import "MainModel.h"
#import "MainDataHelper.h"
#import "UIImageView+WebCache.h"
#import "MainTableViewCell.h"
#import "MainDetailViewController.h"
#import "MJRefresh.h"


@interface MainViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *mainTableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSMutableArray *headerImageArray;

@property (nonatomic, strong) UIScrollView *scrollView;

- (IBAction)leftBarButtonItem:(UIBarButtonItem *)sender;


// 定时器
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int page;

// 下拉刷新,上拉加载需要的属性
@property (nonatomic, assign) int Num;

@end

@implementation MainViewController

- (void)viewDidLoad {
    self.view.backgroundColor = [UIColor whiteColor];
    [super viewDidLoad];
    [self loadData];
    [self loadScrollView];
    [self loadMainTableView];
    
    self.view.backgroundColor = [UIColor cyanColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _Num = 20;
    [self steputRefresh];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cleandata) name:@"cleandata" object:nil];
    
}

#pragma mark--- tableView部分
- (void)loadMainTableView{
    
    UINib *nib = [UINib nibWithNibName:@"MainTableViewCell" bundle:nil];
    [_mainTableView registerNib:nib forCellReuseIdentifier:@"cell"];
    
    
}


#pragma mark - 获取数据
- (void)loadData
{
    
    NSString *string = @"http://api2.pianke.me/pub/today";
    NSString *bodyString = [NSString stringWithFormat:@"auth=W8Um3Eiixm3qtDC8h8GcDrlDJxQMeoN76M8GxpD2Qm3cWP22NFFQx1a7Ps&client=1&deviceid=70D20EF9-AB8B-42FD-937C-7D884DB58895&limit=%d&start=0&version=3.0.6",_Num];
    [MainDataHelper postDataWithUrlString:string andBodyString:bodyString compare:^(id object) {
        self.dataArray = [NSMutableArray array];
        
        NSDictionary *dic = object;
//        NSLog(@"dic====%@",dic);
        NSArray *array = dic[@"data"][@"list"];
        
        for (NSDictionary *dic1 in array) {
            MainModel *model = [[MainModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            [self.dataArray addObject:model];
        }
        [self.mainTableView reloadData];
        
    }];
    
    // 结束下拉刷新
    [self.mainTableView.header endRefreshing];
    // 结束上拉加载
    [self.mainTableView.footer endRefreshing];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MainModel *model = _dataArray[indexPath.row];
    
    MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
   
    
    cell.nameLabel.text = model.name;
    cell.ennameLabel.text = model.enname;

    [cell.MyImageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg] placeholderImage:nil];

    cell.titleLabel.text = model.title;
    cell.contentLabel.numberOfLines = 0;
    [cell.contentLabel sizeToFit];
    cell.contentLabel.font = [UIFont systemFontOfSize:13];
    cell.contentLabel.text = model.content;

     return cell;
//    }
}

#pragma mark - 轮播图
- (void)loadScrollView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    
    _scrollView.bounces = NO;
    
    self.mainTableView.tableHeaderView = _scrollView;
    
    
    self.headerImageArray = [NSMutableArray array];
    NSString *string = @"http://api2.pianke.me/pub/today";
    NSString *bodyString = @"auth=W8Um3Eiixm3qtDC8h8GcDrlDJxQMeoN76M8GxpD2Qm3cWP22NFFQx1a7Ps&client=1&deviceid=70D20EF9-AB8B-42FD-937C-7D884DB58895&limit=10&start=0&version=3.0.6";
    [MainDataHelper postDataWithUrlString:string andBodyString:bodyString compare:^(id object) {
        NSDictionary *dic = object;
        //        NSLog(@"dic====%@",dic);
        NSArray *imageArray = dic[@"data"][@"carousel"];
        NSLog(@"dict2===%@",imageArray);
        
        for (NSDictionary *dic2 in imageArray) {
            MainModel *model = [[MainModel alloc] init];
            [model setValuesForKeysWithDictionary:dic2];
            [self.headerImageArray addObject:model];
        }
    
    NSLog(@"image=====%lu",(unsigned long)_headerImageArray.count);
        for (int i = 0; i < _headerImageArray.count; i++) {
            MainModel *model = _headerImageArray[i];
            
            UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _headerImageArray.count * self.view.frame.size.width, 120)];
            UIImageView *headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * self.view.frame.size.width, 0, self.view.frame.size.width, 200)];
            [headerImageView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:nil];
            [headView addSubview:headerImageView];
            [_scrollView addSubview:headView];
            
            
            headerImageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
            
            [headerImageView addGestureRecognizer:tap];
            
        }
        
        self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * _headerImageArray.count, 0);
        
    }];
}

- (void)tapAction
{
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainDetailViewController *detail = [[MainDetailViewController alloc] init];
    MainModel *model = _dataArray[indexPath.row];
    detail.webStr = model.ID;
    [self.navigationController pushViewController:detail animated:YES];
}


// 上拉加载,下拉刷新方法
- (void)steputRefresh{
    
    self.mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadData];
    }];
    
    self.mainTableView.footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self loadData];
        self.Num += 10;
    }];
    
}


#pragma 清理缓存图片

- (void)cleandata
{
    [[SDImageCache sharedImageCache] clearDisk];
    
    [_mainTableView reloadData];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}




// 定时器放在viewwill里面
- (void)viewWillAppear:(BOOL)animated {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
    // 添加到主线程中去, 返回当前的消息循环对象
    [[NSRunLoop mainRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timer:(NSTimer *)sender {
    self.page++;
    // 这里的self.page < 轮播图的个数 的这个你可以改数字,改了看看,juice知道是干什么的了
    if (self.page < 8) {
        [_scrollView setContentOffset:CGPointMake(self.page * self.view.frame.size.width, 0) animated:YES];
        
    }else {
        self.page = 0;
        [_scrollView setContentOffset:CGPointMake(self.page * self.view.frame.size.width, 0) animated:YES];
    }
}

//释放NSTimer
-(void)viewWillDisappear:(BOOL)animated
{
    [self.timer invalidate];
    self.timer = nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark--- 左侧button点击事件



- (IBAction)leftBarButtonItem:(UIBarButtonItem *)sender {
    
        [self.sideMenuViewController presentLeftMenuViewController];
}
@end
